package com.shujia.spark.core

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo18PI {
  def main(args: Array[String]): Unit = {
    //配置文件
    val conf: SparkConf = new SparkConf().setAppName("Pi")
      //提交到服务器需要将这行代码注释掉
    // .setMaster("local")

    //创建spark对象
    val sc = new SparkContext(conf)

    //产生一个随机数组
    val list: Range = 0 until 1000000

    //构建一个RDD
    val listRDD: RDD[Int] = sc.parallelize(list)

    //模拟生成点
    val pointRDD: RDD[(Double, Double)] = listRDD.map(i =>{
      //模拟点（Random.nextDouble随机产生一个0到1的数）
      val x:Double =Random.nextDouble() * 2-1
      val y:Double =Random.nextDouble() * 2-1
      (x,y)
    })

    //取出圆内的点
    val yuanPointRDD: RDD[(Double, Double)] = pointRDD.filter{
      case (x:Double,y:Double) =>
        //通过计算点到圆心的距离来判断点是否在圆里
      x * x + y * y < 1
    }

    //计算PI
   val PI: Double = yuanPointRDD.count().toDouble / list.length * 4

    println(PI)
  }
}
